var win = null;
function NewWindow(mypage,myname,w,h,scroll){
   LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
   TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
   settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable';
   win = window.open(mypage,myname,settings)
   if(win.window.focus){
      win.window.focus();
   }
}

function Redirector()
{
   window.location.replace('http://'+window.location.host+window.location.pathname);
}

function rand(min, max)
{
   var argc = arguments.length;
   if (argc === 0)
   {
      min = 0;
      max = 2147483647;
   } else if (argc === 1)
   {
      throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
   }
   return Math.floor(Math.random() * (max - min + 1)) + min;
}


/*
 * Get Size of Page,
 * return array with four elements: [0] - window width, [1] - window height, [2] - screen width, [3] - screen height
 */
function getPageSize()
{
   var xScroll, yScroll;
   if (window.innerHeight && window.scrollMaxY)
   {
      xScroll = window.innerWidth + window.scrollMaxX;
      yScroll = window.innerHeight + window.scrollMaxY;
   } else if (document.body.scrollHeight > document.body.offsetHeight)
   { // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
   } else 
   { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
   }

   var windowWidth, windowHeight;
   if (self.innerHeight) 
   { // all except Explorer
      if(document.documentElement.clientWidth)
      {
         windowWidth = document.documentElement.clientWidth; 
      } else 
      {
         windowWidth = self.innerWidth;
      }
      windowHeight = self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientHeight) 
   { // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
   } else if (document.body) 
   { // other Explorers
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
   }

   if(yScroll < windowHeight)
   {
      pageHeight = windowHeight;
   } else { 
      pageHeight = yScroll;
   }

   if(xScroll < windowWidth)
   { 
      pageWidth = xScroll;    
   } else 
   {
      pageWidth = windowWidth;
   }

   return [pageWidth,pageHeight,windowWidth,windowHeight];
}

/*
 * Get page scroll X, Y as array
 * [0] - x, [1] - y
 */
function getPageScroll()
{
   var xScroll =0, yScroll = 0;
   if (self.pageYOffset)
   {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
   } else if (document.documentElement && document.documentElement.scrollTop)
   {    // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
   } else if (document.body) 
   {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft; 
   }

   return [xScroll,yScroll];
}

/**
 * Get current element position: [left, top]
 */
function getCurPosition(el)
{
   var left = top = 0;
   if (el.offsetParent)
   {
      do
      {
         left += el.offsetLeft;
         top += el.offsetTop;
      } while (el = el.offsetParent);
   }
   return [left,top];
}

/*************************************************/
/**  Functions which use JQuery                 **/


/**
* Enable || Disable button in document
*/
function DisButton(btn, OnOff)
{
   var button = $(btn);
   button.attr("disabled",OnOff);
   if(OnOff == true)
   {
      button.addClass("disabledButton");
   } else {
      button.removeClass();
   }
}

/**
* Drop TR in Table by being clicked button in this TR
*/
function DropTr(btn)
{
   while (btn.tagName != 'TR') btn = btn.parentNode;
   btn.parentNode.removeChild(btn);
}

function ColorizeTr(table)
{
   $("#"+table+" tr").each(function(index)
   {
      if(index % 2 == 0)
      {
         $(this).addClass("odd");
      } else
      {
         $(this).removeClass("odd");
      }
   });
}

function MarkTr(el)
{
   var checked = el.checked;
   while(el.tagName != 'TR') el = el.parentNode;
   if(checked)
   {
      $(el).addClass('mark');
   } else
   {
      $(el).removeClass('mark');
   }
}


function Css2FormInput(box)
{
   if(typeof box == 'undefined' || box == ''){ 
      box = '';
   } else {
      box = '#'+box + ' ';
   }
   $(box + 'input').bind('focus', function(){
      $(this).addClass('hovered');
      $(box + 'label[for*=' + $(this).attr('id') + ']').addClass('chosen');
   });
   $(box + 'input').bind('blur', function(){
      $(this).removeClass('hovered');
      $(box + 'label[for*=' + $(this).attr('id') + ']').removeClass('chosen');
   });
}

function Close(id)
{
   $('#' + id).remove();
}

// IMPROVE JQUERY
/**
 * AutoGrow Textarea fields
 */
jQuery.fn.autogrow = function() 
{
   jQuery(this).each(function(){
      if(this.scrollHeight  > this.offsetHeight)
      {
         this.style.height = this.scrollHeight + 'px';
      }
   });
   jQuery(this).bind('keyup', function(){
      if(this.scrollTop > 0)
      {
         this.style.height = this.offsetHeight + 'px';
      }
   });
   return this;
}

/**
 * Clone TR
 */
jQuery.fn.cloneTr = function(options)
{
   var settings = {
      sample:'-2',
      place:'first' // WHERE TO PLACE CLONED TR
   };
   settings = jQuery.extend(settings, options);
   var tr = $(this).find('tr').get();
   settings.sample = parseInt(settings.sample);

   if(tr.length && Math.abs(settings.sample) <= tr.length)
   {
      if(settings.sample < 0) var p = tr.length + settings.sample;
      else p = settings.sample;

      switch(settings.place)
      {
         case 'after':settings.place = p + 1;break;
         case 'before':settings.place = p;break;
         case 'last':settings.place = tr.length;break;
         case 'first':settings.place = 0;break;
         default:settings.place = parseInt(settings.place);
      }
      var el = $(tr[p]).clone(true).map(function(){
         $(':text', this).attr({
            value:'',
            name:$(':text', this).attr('name').replace(/\d/, '')
            });return this;
      });
      if(settings.place == tr.length) el.insertAfter(tr[settings.place - 1]);
      else el.insertBefore(tr[settings.place]);
   }
   return this;
}

jQuery.fn.toggleCheckbox = function(options)
{
   var settings = {
      button: '#tuggleButton',
      uncheckText: 'Uncheck All',
      checkText: 'Check All'
   };
   settings = jQuery.extend(settings, options);
   var cont = this;
   $(settings.button).attr('rel', 'check').bind('click', function(){
      if($(this).attr('rel') == 'check')
      {
         $(this).attr('rel', 'uncheck').val(settings.uncheckText);
         $(' input[type=checkbox]', cont).attr('checked','checked');
      } else
      {
         $(this).attr('rel', 'check').val(settings.checkText);
         $(' input[type=checkbox]', cont).attr('checked','');
      }
   });
}


// STARTUP ACTIONS
$(document).ready(function(){
   $('input').bind('focus', function(){
      $(this).addClass('hovered');
      $('label[for*=' + $(this).attr('id') + ']').addClass('chosen');
   });
   $('input').bind('blur', function(){
      $(this).removeClass('hovered');
      $('label[for*=' + $(this).attr('id') + ']').removeClass('chosen');
   });
   $('.autogrow').autogrow();
});


/**
  * Switch languages in form
  */
function SwitchLang(lang)
{
   // Switch editors
   for(var x in editors)
   {
      document.getElementById('f_'+x+'_'+current_lang).value = editors[x].val();
      editors[x].val(document.getElementById('f_'+x+'_'+lang).value);
   }

   // Switch Fields in SPAN.multilang
   $('span.multilang[rel='+lang+']').css('display','inline');
   $('span.multilang[rel!='+lang+']').css('display','none');

   // Switch Language TAB
   $('#langSwitcher a').removeClass('current');
   $('#lang_'+lang).addClass('current');
   current_lang = lang;
}

function loadCropper(el, field, container)
{
   var $dialog = $('<div></div>');
   $link = $(el);
   $dialog.load($link.attr('href')+'?id='+field+'&container='+container+'&'+rand(1,10000)).dialog({
      modal:true,
      resizable:false,
      position:[10,10],
      title: $link.attr('title'),
      width: 1000,
      close: function(event, ui){
         $('#cropperContainer').parent().remove();
         $(this).dialog('destroy');
      }
   });
   return false;
}
function DelThumb(field)
{
   field = $(field).parent().parent().parent();
   $('input', field).val('delete');
   $('img[rel!=button]', field).remove();
   $('img', field).css('display','');
   $('span[rel=del_img]', field).css('display','none');
}

function CommitForm(form)
{
   for(var x in editors)
   {
      document.getElementById('f_'+x+'_'+current_lang).value = editors[x].val();
   }
   
   $('.ui-sortable').each(function(){
      var p_index = 1;
      $('input[rel=position]', this).each(function(){$(this).val(p_index);p_index++;});
   });
   document[form].submit();
}

function ResortFieldset(e, ui)
{
   var i = 1;
   $('input[rel=position]', ui.item.parent()).each(function(){
      $(this).val(i);
      i++;
   });
}

function DeleteInFieldset(el, fset, id)
{
	//fieldset
	while(el.className != 'fieldset') el = el.parentNode;
	$(el).replaceWith('<input type="hidden" name="delete_fieldset['+fset+'][]" value="'+id+'" />');
}


function deleteComment(id)
{
   $("<div>Do you realy want to delete this comment(s)?</div>").dialog({
      modal: true,
      buttons:{
         "Yes": function(){
            var dialog = this;
            $.get(
               "/api.json",
               {method:'comments.delete', data: {id: id}},
               function(r){
                  if(r)
                  {
                     $('#comment_'+ id).remove();
                  }
                  $(dialog).dialog("destroy");
               },
               'json'
            );
         },
         "Cancel": function(){$(this).dialog("destroy");}
      }
   });
}
// TODO: разработать единую систему (класс) - для выдачи алертов, конфирмейшенов

function switchCommentActiveState(id)
{
   var sw2state = $('#comment_'+id).hasClass('inactive') ? 1 : 0;
   $.get(
      "/api.json",
      {method:'comments.switchActive', data: {id: id, active: sw2state}},
      function(r)
      {
         if(r) $('#comment_'+id).toggleClass('inactive')
            .find('a.i_on, a.i_off').toggleClass('i_on').toggleClass('i_off');
      },
      'json'
   );
}


var meccano = {
   notification: function(type, text, options)
   {
      type = type != 'success' ? 'failure' : type;
      if(typeof(text) == 'undefined') return false;
      this._notification.setOptions(options);
      this._notification.createBox();
      this._notification.postMessage(text);
   },
   notification_success: function(text, options)
   {
      options = typeof(options) != "object" ? {} : options;
      options["class"] = 'mc_notif_success';
      this.notification('success', text, options);
   },
   notification_failure: function(text)
   {
      options = typeof(options) != "object" ? {} : options;
      options["class"] = 'mc_notif_failure';
      this.notification('failure', text, options);
   },
   dialog: function(text, options)
   {
      this.notification('dialog', text, {buttons: options, timeout: 0});
   },
   hideNotification: function()
   {
      this._notification.removeBox();
   },
   _notification: {
      def_options: {
         timeout: 5000,
         modal: false,
         "class": "mc_notif_info"
      },
      options: {},
      setOptions: function(options)
      {
         options = typeof(options) == 'object' ? options : {};
         this.options = $.extend(this.def_options, options);
      },
      createBox: function()
      {
         if($('#mc_notif_box').size() == 0)
         {
            if(this.options['modal'])
            {
               $('body')
                  .append('<div class="mc_modal_overlay" style="display:none;"></div>')
                  .find(".mc_modal_overlay")
                  .fadeIn(400);
            }
            $('body')
               .append('<div class="mc_notif_box '+ this.options["class"] +'" id="mc_notif_box">' +
                           '<div class="mc_notif_header">' +
                              '<span></span>' +
                              '<a href=""></a>' +
                              '<div class="clear"></div>' +
                           '</div>' +
                           '<div class="mc_notif_message"></div>' +
                           '<div class="mc_buttons"></div>' +
                        '</div>')
               .find('#mc_notif_box')
               .find(".mc_notif_header a")
               .click(function(){
                  meccano._notification.removeBox();
                  return false;
               });
            if('buttons' in this.options)
            {
               $("#mc_notif_box .mc_buttons").show();
               for(var x in this.options.buttons)
               {
                  $("#mc_notif_box .mc_buttons").append('<input type="button" value="'+ x +'" />').find("input[value="+x+"]").click(this.options.buttons[x]);
               }
            }
            $("#mc_notif_box").fadeIn(400);               
            if(this.options.timeout > 0) window.setTimeout(function(){meccano._notification.removeBox();}, this.options.timeout*1+400);
         }
      },
      removeBox: function()
      {
         this.options = $.extend(this.options, this.def_options);
         if(this.options.modal)
         {
            $(".mc_modal_overlay").fadeOut(400, function(){$(this).remove();});
         }
         $('#mc_notif_box').fadeOut(400, function(){$(this).remove();});
      },
      postMessage: function(text)
      {
         $("#mc_notif_box .mc_notif_message").text(text);
      }
   }
};